package com.wxq.product.service.impl;


import com.wxq.common.to.SkuReductionTO;
import com.wxq.common.utils.R;
import com.wxq.product.entity.*;
import com.wxq.product.feign.CouponFeignService;
import com.wxq.product.service.*;
import com.wxq.product.vo.*;
import com.wxq.product.entity.SkuImagesEntity;
import com.wxq.product.entity.SkuInfoEntity;
import com.wxq.product.entity.SpuInfoEntity;
import com.wxq.product.service.SkuInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxq.common.utils.PageUtils;
import com.wxq.common.utils.Query;

import com.wxq.product.dao.SkuInfoDao;
import org.springframework.util.StringUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

@Slf4j
@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    TemplateEngine templateEngine;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>().lambda().eq(SkuInfoEntity::getSkuId,"1")
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SpuInfoEntity spuInfoEntity, List<Skus> skuses) {
        //保存sku基本信息
        skuses.stream().forEach(skus -> {
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(skus,skuInfoEntity);
            skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
            skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            skuInfoEntity.setSaleCount(0L);
            String defaultImage = "";
            for (Images image : skus.getImages()) {
                if (image.getDefaultImg() == 1){
                    defaultImage = image.getImgUrl();
                }
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                this.save(skuInfoEntity);
            }
            //批量保存sku图片
            Long skuId = skuInfoEntity.getSkuId();
            List<SkuImagesEntity> skuImagesEntities = skus.getImages().stream().map(images -> {
                return new SkuImagesEntity(){{
                    setDefaultImg(images.getDefaultImg());
                    setSkuId(skuId);
                    setImgUrl(images.getImgUrl());
                }};
            }).filter(skuImagesEntity -> {
                return !StringUtils.isEmpty(skuImagesEntity.getImgUrl());
            }).collect(Collectors.toList());
            skuImagesService.saveBatch(skuImagesEntities);
            //批量保存sku属性
            List<SkuSaleAttrValueEntity> collect = skus.getAttr().stream().map(attr -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr,skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(spuInfoEntity.getId());
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(collect);
            //保存优惠，满减等信息
            SkuReductionTO skuReductionTO = new SkuReductionTO();
            BeanUtils.copyProperties(skus,skuReductionTO);
            skuReductionTO.setSkuId(skuId);
            if (skuReductionTO.getFullCount() > 0 || skuReductionTO.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                R r = couponFeignService.saveReducttion(skuReductionTO);
                if (r.getCode() != 0){
                    log.error("调用远程服务 yomall-coupon 保存SKU优惠信息失败");
                }
            }
        });



    }

    /**
     * sku检索
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper <>();
        String key = (String)params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(wrapper -> {
                wrapper.eq("sku_id", key).or().like("sku_name", key);
            }); }
        String brandId = (String)params.get("brandId");
        if (!StringUtils.isEmpty(brandId)  && !"0".equalsIgnoreCase(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }
        String catelogId = (String)params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)  && !"0".equalsIgnoreCase(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        String min = (String)params.get("min");
        if (!StringUtils.isEmpty(min)) {
            queryWrapper.ge("price", min);
        }
        String max = (String)params.get("max");
        if (!StringUtils.isEmpty(max)  && !"0".equalsIgnoreCase(max)) {
            queryWrapper.le("price", max);
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkuBySpuId(Long spuId) {
         List<SkuInfoEntity> skuInfoEntities = this.list(
                 new QueryWrapper<SkuInfoEntity>().eq("spu_id",spuId)
         );
         return skuInfoEntities;
    }

    /**
     * sku详情页
     * @param skuId
     * @return
     */
    @Override
    public SkuItemVO item(Long skuId) {
        SkuItemVO skuItemVO = new SkuItemVO();
        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() ->{
            //1.sku基本信息 pms_sku_info
            SkuInfoEntity skuInfo = getById(skuId);
            skuItemVO.setSkuInfo(skuInfo);
            return skuInfo;
        },executor);
        CompletableFuture<Void> saleAttrFuture = skuInfoFuture.thenAcceptAsync((res) ->{
            //3.spu的销售属性组合
            List<SkuSaleAttrVO> saleAttrs = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            skuItemVO.setSaleAttrs(saleAttrs);
        },executor);
        CompletableFuture<Void> descFuture = skuInfoFuture.thenAcceptAsync((res) ->{
            //4.spu商品介绍
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVO.setSpuDesc(spuInfoDescEntity);
        },executor);
        CompletableFuture<Void> baseAttrFuture = skuInfoFuture.thenAcceptAsync((res) ->{
            //5.spu规格参数
            List<SpuAttrGroupVO> groupAttrs = attrGroupService.getAttrGroupWithAttysBySpuId(
                    res.getCatalogId(),res.getSpuId()
            );
            skuItemVO.setGroupAttrs(groupAttrs);
        },executor);
        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() ->{
            //2.sku图片信息 pms_sku_images
            List<SkuImagesEntity> images = skuImagesService.getImagesBySkuId(skuId);
            skuItemVO.setImages(images);
        },executor);
        try {
            //等待所有任务执行完成
            CompletableFuture.allOf(saleAttrFuture,descFuture,baseAttrFuture,imageFuture).get();
        }catch (InterruptedException e){
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }

  /*      //1.sku基本信息 pms_sku_info
        SkuInfoEntity skuInfo = getById(skuId);
        skuItemVO.setSkuInfo(skuInfo);
        Long spuId = skuInfo.getSpuId();
        Long catalogId = skuInfo.getCatalogId();*/
        //TOOO 查询库存
        skuItemVO.setHasStock(true);
     /*   //2.sku图片信息 pms_sku_images
        List<SkuImagesEntity> images = skuImagesService.getImagesBySkuId(skuId);
        skuItemVO.setImages(images);
        //3.spu销售属性组合
        List<SkuSaleAttrVO> saleAttrs = skuSaleAttrValueService.getSaleAttrsBySpuId(spuId);
        skuItemVO.setSaleAttrs(saleAttrs);
        //4.spu商品介绍
        SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(spuId);
        skuItemVO.setSpuDesc(spuInfoDescEntity);
        //5.spu规格参数
        List<SpuAttrGroupVO> groupAttrs = attrGroupService.getAttrGroupWithAttysBySpuId(catalogId,spuId);
        skuItemVO.setGroupAttrs(groupAttrs);*/
        return skuItemVO;
    }

    /**
     * 创建静态页面
     * @param skuId
     */
    @Override
    public void createHtml(Long skuId) {
        // 获取页面数据
        executor.submit(() ->{
            PrintWriter writer = null;
            try {
                SkuItemVO skuItemVO = item(skuId);
                // 创建thymeleaf上下文对象
                Context context = new Context();
                // 把数据放入上下文对象
                context.setVariable("skuItemVO",skuItemVO);
                // 创建输出流，指定输出目的地
                // 上线后，这个目的地应该配置为 nginx 的一个资源目录
                File file = new File("/Users/wuxiangqi/nginx/html"+skuId+".html");
                writer = new PrintWriter(file);
                // 执行页面静态化方法
                templateEngine.process("item",context,writer);
            } catch (Exception e){
                log.error("页面静态化出错：{}",e,skuId.toString());
            }finally {
                if (writer != null){
                    writer.close();
                }
            }
        });
    }

}